#include <iostream>
#include <thread>
#include <atomic>

//使用std::automic变量来控制，多个线程的结束，


using namespace std;
//atomic<bool> g_flag=false; 写法编译报错
atomic<bool> g_flag;


void fun()
{
    chrono::milliseconds dura(1000);
    while (g_flag==false) {
        cout << "thread id = " << std::this_thread::get_id() << " 运行中..." << endl;
        std::this_thread::sleep_for(dura);
    }
    cout << "thread id = " << std::this_thread::get_id() << " 运行中结束..." << endl;
    return ;
}

int main()
{
    //在构造函数或者开局才能初始化atomic变量
    g_flag=false;
    cout << "Hello World!" << endl;
    std::thread myobj1(fun);
    std::thread myobj2(fun);
    std::chrono::milliseconds dura(5000);
    //5秒钟
    std::this_thread::sleep_for(dura);
    g_flag = true;
    //对原子对象的写操作，让线程自行运行结果；
    myobj1.join();
    myobj2.join();
    cout << "程序执行完毕，退出" << endl;

    return 0;
}
